from django.http import JsonResponse
from django.views import View
from homes.models import House
from orders.models import Order

class HouseTuiJianView(View):
    '''首页房屋推荐'''
    def get(self, request):
        '''获取房屋图片'''
        try:
            houses = House.objects.order_by('order_count')[:5]

        except Exception as e:
            return JsonResponse({'errno': 400,
                                 'errmsg': '获取图片地址失败'})
        # 构建返回字典
        data = []
        for house in houses:
            data.append({
                "house_id": house.id,
                "img_url":      + house.index_image_url,
                "title": house.title})
        return JsonResponse({'errno': 0,
                             'errmsg': 'ok',
                             'data': data})

class House_detail(View):
    def get(self,request):
        house_id = request.GET.get('house_id')
        if request.user.is_authenticated:
            user = request.user #当前用户对象
            user_id = user.id
        else:
            user_id = -1

        house = House.objects.get(id = house_id)
        landlord = house.user  #房东对象
        house_dict = {
            'acreage':house.acreage,
            'address':house.address,
            'beds':house.beds,
            'capacity':house.capacity,
            'comments':[],
            'deposit':house.deposit,
            'facilities':[facility.id for facility in house.facility],
            'hid': house.id,
            'max_days': house.max_days,
            'min_days': house.min_days,
            'price': house.price,
            'room_count': house.room_count,
            'title': house.title,
            'unit': house.unit,
            'user_avatar':landlord.avator,
            'user_id':landlord.id,
            'user_name':landlord.real_name,
            'img_urls':[]}

        orders = Order.objects.filter(house_id =id,
                                      status = 4,
                                      comment__isnull =False).order_by('update_time' )[0:5]

        for order in orders:
            house_dict['comments'].append({
                'comment':order.comment,
                'ctime': order.create_time,
                'user_name':order.user.real_name})
        dict = {
            'data':{
                'house':house_dict,
                'user_id':user_id},
            "errmsg": "OK",
            "errno": "0"
        }
        return JsonResponse(dict)

